
package com.huizhan.web.controller;
 
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Sort.*;
//import org.springframework.jdbc.core.JdbcTemplate;
import io.swagger.annotations.*;
import java.io.*;
import java.util.*;

import javax.servlet.http.*;
import com.huizhan.web.dao.*;
import com.huizhan.web.model.*;
import com.huizhan.web.view.*;

/**
 * 电子票记录api
 */
 
@Api(tags = "TicketRecord",description = "电子票记录")
@RestController
public class TicketRecordController {
    
    @Autowired
    private TicketRecordDao dao;
   
    @Autowired
    private TicketDao ticketDao;
    
    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值
    
    @Value("${uploadFile.resourceHandler}")
    private String resourceHandler;//请求 url 中的资源映射，不推荐写死在代码中，最好提供可配置，如 /uploadFiles/**

    @Autowired
    private TicketTypeDao ticketTypeDao;

    /**
     * 获取电子票记录集合
     * @return api结果
     */
    @ApiOperation(value = "获取电子票记录集合")
    @RequestMapping(value =  "/api/TicketRecord/",method = {RequestMethod.GET})
    public ApiResult<List<TicketRecord>> Get(){
         ApiResult<List<TicketRecord>> result=new ApiResult<List<TicketRecord>>();
        try 
        {
            List<TicketRecord> res = dao.findAll();
            result.setData(res);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }

    /**
     * 根据ID获取电子票记录信息
     * @param id 电子票记录ID
     * @return api结果
     */
    @ApiOperation(value = "根据ID获取电子票记录信息")
    @RequestMapping(value =  "/api/TicketRecord/{id}",method = {RequestMethod.GET})
    public ApiResult<TicketRecord> Get(@PathVariable Long id){
        ApiResult<TicketRecord> result=new ApiResult<TicketRecord>();
        try
        {
            TicketRecord model= dao.getOne(id);
            result.setData(model);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }


    /**
     * 根据类型ID和手机号获取电子票记录信息
     * @param id 电子票记录ID
     * @return api结果
     */
    @ApiOperation(value = "根据类型ID和手机号获取电子票记录信息")
    @RequestMapping(value =  "/api/TicketRecord/Phone/",method = {RequestMethod.POST})
    public ApiResult<List<ApiTicket>> POST(Long ticketTypeId,String phone,HttpServletRequest request){
        ApiResult<List<ApiTicket>> result=new ApiResult<List<ApiTicket>>();
        try
        {
            List<Ticket> list= ticketDao.findByTicketTypeIdAndNameAndIsPassage(ticketTypeId,phone,0);

            List<ApiTicket> apiTickets=new ArrayList<ApiTicket>();

            for (Ticket ticket : list) {
                ApiTicket api=new ApiTicket();

                api.setCode(ticket.getIdNumber());
                api.setUrl(request.getScheme() + "://" + request.getServerName()+"/"+ticket.getTicketTypeId()+","+ticket.getCode());
                apiTickets.add(api);
            }

            result.setData(apiTickets);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }


    /**
     * 修改电子票记录信息
     * @param id 电子票记录ID
     * @param model 电子票记录信息
     * @return api结果
     */
    @ApiOperation(value = "修改电子票记录信息")
    @RequestMapping(value =  "/api/TicketRecord/{id}",method = {RequestMethod.PUT})
    public ApiResult<TicketRecord> Edit(@PathVariable Long id,@RequestBody TicketRecord model){
        ApiResult<TicketRecord> result=new ApiResult<TicketRecord>();
        try
        {
            model.setTicketRecordId(id);
            dao.save(model);
            result.setData(model);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return  result;
    }



    /**
     * 添加电子票记录信息
     * @param model 电子票记录信息
     * @return api结果
     */
    @ApiOperation(value = "添加电子票记录信息")
    @RequestMapping(value =  "/api/TicketRecord/",method = {RequestMethod.POST})
    public ApiResult<List<ApiTicket>> Add(@RequestBody TicketRecord model,HttpServletRequest request){
        ApiResult<List<ApiTicket>> result=new ApiResult<List<ApiTicket>>();
        try
        {
            if(model.getNumber()<=0){
                result.setHasError(false);
                result.setMessage("电子票数量不能小于1");
            }else{
                model.setCreateDate(new Date());
                if(model.getType()==null){
                    model.setType(0L);
                    model.setName("云尚系统");
                }
                if(model.getType()==1L){
  
                }else if(model.getType()==2L){
                    String newFilePath=new Date().getTime()+".txt";
                    String c=uploadFileLocation+newFilePath;
                    File file = new File(c);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    String url=model.getUrl();
                    model.setUrl(request.getScheme() + "://" + request.getServerName() +resourceHandler.replace("*","")+ newFilePath);
                    dao.save(model);
                    List<Ticket> list=new ArrayList<Ticket>();
                    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(c), "UTF-8"));
                    
                    for (Long i=0L;i<model.getNumber();i++){
                        Ticket ticket = new Ticket();
                        ticket.setTicketTypeId(model.getTicketTypeId());
                        ticket.setTicketRecordId(model.getTicketRecordId());
                        ticket.setIdNumber(UUID.randomUUID().toString());
                        ticket.setBanner(url);
                        ticket.setProjectId(model.getProjectId());
                        ticket.setIsPassage(0);
                        ticket.setCreateDate(new Date());
                        out.write(ticket.getIdNumber());
                        out.newLine();
                        //ticketDao.save(ticket);
                        //list.add(ticket);
                    }
                   ticketDao.saveAll(list);
                    out.flush();
                    out.close();
                }else if(model.getType()==3L){
                    String newFilePath=new Date().getTime()+".txt";
                    String c=uploadFileLocation+newFilePath;
                    File file = new File(c);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    String url=model.getUrl();
                    model.setUrl(request.getScheme() + "://" + request.getServerName() +resourceHandler.replace("*","")+ newFilePath);
                    dao.save(model);
                    List<Ticket> list=new ArrayList<Ticket>();
                    List<Ticket> tickets= ticketDao.findByTicketTypeId(model.getTicketTypeId());
                    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(c), "UTF-8"));
                    for (Long i=0L;i<model.getNumber();i++){
                        Ticket ticket = new Ticket();
                        ticket.setTicketTypeId(model.getTicketTypeId());
                        ticket.setTicketRecordId(model.getTicketRecordId());
                        ticket.setIdNumber(UUID.randomUUID().toString());
                        ticket.setBanner(url);
                        ticket.setProjectId(model.getProjectId());
                        ticket.setIsPassage(0);
                        this.getCode(ticket,tickets);
                        ticket.setCreateDate(new Date());
                        out.write(request.getScheme() + "://" + request.getServerName()+"/"+ticket.getTicketTypeId()+","+ticket.getCode());
                        out.newLine();
                        tickets.add(ticket);
                        list.add(ticket);
                        //ticketDao.save(ticket);
                    }
                    ticketDao.saveAll(list);
                    
                    out.flush();
                    out.close();
                }else{
                    TicketType project=ticketTypeDao.getOne(model.getTicketTypeId());

                    model.setTypeName(project.getName());
                    model.setProjectId(project.getProjectId());
                    model.setType(0L);
                    
                    dao.save(model);

                    List<Ticket> lists=new ArrayList<Ticket>();
                    List<ApiTicket> list=new ArrayList<ApiTicket>();
                    List<Ticket> tickets= ticketDao.findByTicketTypeId(model.getTicketTypeId());

                    for (Long i=0L;i<model.getNumber();i++){
                        Ticket ticket = new Ticket();
                        ApiTicket api=new ApiTicket();
                        ticket.setTicketTypeId(model.getTicketTypeId());
                        ticket.setTicketRecordId(model.getTicketRecordId());
                        ticket.setIdNumber(UUID.randomUUID().toString());
                        ticket.setProjectId(model.getProjectId());
                        ticket.setIsPassage(0);
                        ticket.setName(model.getPhone());
                        this.getCode(ticket,tickets);
                        ticket.setCreateDate(new Date());
                        tickets.add(ticket);
                        //ticketDao.save(ticket);
                        api.setCode(ticket.getIdNumber());
                        api.setUrl(request.getScheme() + "://" + request.getServerName()+"/"+ticket.getTicketTypeId()+","+ticket.getCode());
                        list.add(api);
                        lists.add(ticket);
                    }
                    ticketDao.saveAll(lists);
                    result.setData(list);
                }
            }
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
    


    /**
     * 获取码值
     * @param ticket
     */
    private void getCode(Ticket ticket,List<Ticket> list){
        String no=TenpayUtil.random(7);
        for (Ticket ticket2 : list) {
            if(ticket2.getCode().equals(no)){
                getCode(ticket,list);
            }
        }
        ticket.setCode(no);
    }

    /**
     * 查询赠票记录集合
     * @param model 账号信息
     * @return api结果
     */
    @ApiOperation(value = "查询赠票记录集合")
    @RequestMapping(value =  "/api/TicketRecord/Search",method = {RequestMethod.POST})
    public ApiResult<List<TicketRecord>> Search(@RequestBody PageTicketRecord model){
         ApiResult<List<TicketRecord>> result=new ApiResult<List<TicketRecord>>();
         
        try
        {    
            PageRequest pageable = PageRequest.of(model.getPageIndex(),model.getPageSize(),Direction.DESC,"ticket_record_Id") ;            
            Page<TicketRecord> page = dao.findByWhere(model.getName(),model.getPhone(),model.getProjectId(),model.getTicketTypeId(),model.getType(),pageable);
            result.setData(page.getContent());
            result.setTotal(page.getTotalElements());
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除电子票记录信息
     * @param id 电子票记录ID
     * @return api结果
     */
    @ApiOperation(value = "删除电子票记录信息")
    @RequestMapping(value =  "/api/TicketRecord/{id}",method = {RequestMethod.DELETE})
    public ApiResult<Object> Delete(@PathVariable  Long id){
        ApiResult<Object> result=new ApiResult<Object>();
        try 
        {
            ticketDao.deleteByTicketRecordId(id);
            dao.deleteById(id);
        }catch(Exception e){
            result.setHasError(true);
            result.setMessage(e.getMessage());
        }
        return result;
    }
}
